package com.lambkit.db.dialect;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.dialect.DriverNamePool;
import cn.hutool.log.StaticLog;

/**
 * @author yangyong(孤竹行)
 */
public class DialectFactory implements DriverNamePool {
    /**
     * 根据驱动名创建方言<br>
     * 驱动名是不分区大小写完全匹配的
     *
     * @param driverName JDBC驱动类名
     * @return 方言
     */
    public static IDialect newDialect(String driverName) {
        final IDialect dialect = internalNewDialect(driverName);
        StaticLog.debug("Use Dialect: [{}].", dialect.getClass().getSimpleName());
        return dialect;
    }

    /**
     * 根据驱动名创建方言<br>
     * 驱动名是不分区大小写完全匹配的
     *
     * @param driverName JDBC驱动类名
     * @return 方言
     */
    private static IDialect internalNewDialect(String driverName) {
        if (StrUtil.isNotBlank(driverName)) {
            if (DRIVER_MYSQL.equalsIgnoreCase(driverName) || DRIVER_MYSQL_V6.equalsIgnoreCase(driverName)) {
                return new MysqlDialect();
            } else if (DRIVER_ORACLE.equalsIgnoreCase(driverName) || DRIVER_ORACLE_OLD.equalsIgnoreCase(driverName)) {
                return new OracleDialect();
            } else if (DRIVER_SQLLITE3.equalsIgnoreCase(driverName)) {
                return new Sqlite3Dialect();
            } else if (DRIVER_POSTGRESQL.equalsIgnoreCase(driverName)) {
                return new PostgreSqlDialect();
//            } else if (DRIVER_H2.equalsIgnoreCase(driverName)) {
//                return new LambkitH2Dialect();
            } else if (DRIVER_SQLSERVER.equalsIgnoreCase(driverName)) {
                return new SqlServerDialect();
//            } else if (DRIVER_PHOENIX.equalsIgnoreCase(driverName)) {
//                return new LambkitPhoenixDialect();
            }
        }
        // 无法识别可支持的数据库类型默认使用ANSI方言，可兼容大部分SQL语句
        return new AnsiSqlDialect();
    }

    public static IDialect create(String dialectName) {
        if (StrUtil.isNotBlank(dialectName)) {
            return ReflectUtil.newInstance(dialectName);
        }
        // 无法识别可支持的数据库类型默认使用ANSI方言，可兼容大部分SQL语句
        return new AnsiSqlDialect();
    }
}
